<?php

    ##################################################
    #
    # Copyright (c) 2004-2006 OIC Group, Inc.
    # Copyright (c) 2006 Maxim Mueller
    # Written and Designed by James Hunt
    #
    # This file is part of Exponent
    #
    # Exponent is free software; you can redistribute
    # it and/or modify it under the terms of the GNU
    # General Public License as published by the Free
    # Software Foundation; either version 2 of the
    # License, or (at your option) any later version.
    #
    # GPL: http://www.gnu.org/licenses/gpl.txt
    #
    ##################################################
    /**
    * Change logs
    * Sep 7, 2011 - trungdt - Fix bug: check Define DEFAULT_VIEW and LANG_CHARSET
    */


    define('SYS_LANG',1);

    /**
    * Change logs
    * Feb 2, 2011 - trungdt - exponent_lang_loadtext
    *                         Add language file for default text
    * Sep 8. 2011 - trungdt- Add auto load default language text into memory at the init, then, Add the language into $_TR every time template engine parse the template view
    */

    /*
    define('SYS_LANG_MODULE',	1);
    define('SYS_LANG_VIEW',		2);
    define('SYS_LANG_ACTION',	3);
    */
    /**
    * ABSoft Default language text, Will be merge with $_TR each time template parsing
    * 
    * @var array
    * @author trungdt
    * @since Sep 8, 2011 
    */
    $_AB_TEMPLATE_DEFAULT=array();
    /**
    * Sep 8, 20101 - trungdt - End
    */

    function exponent_lang_list() {
        $dir = BASE.'subsystems/lang';
        $langs = array();
        if (is_readable($dir)) {
            $dh = opendir($dir);
            while (($f = readdir($dh)) !== false) {
                if (substr($f,-4,4) == '.php') {
                    $info = include($dir.'/'.$f);
                    $langs[substr($f,0,-4)] = $info['name'];
                }
            }
        }
        return $langs;
    }
    function exponent_lang_full () {
        $dir = BASE.'subsystems/lang';
        $langs = array();
        if (is_readable($dir)) {
            $dh = opendir($dir);
            while (($f = readdir($dh)) !== false) {
                if (substr($f,-4,4) == '.php') {
                    $info = include($dir.'/'.$f);
                    $langs[substr($f,0,-4)] = $info;
                }
            }
        }
        return $langs;
    }

    function exponent_lang_get_number($name) {
        $dir = BASE.'subsystems/lang';
        $langs = array();
        if (is_readable($dir)) {
            $dh = opendir($dir);
            while (($f = readdir($dh)) !== false) {
                if (substr($f,-4,4) == '.php') {
                    $info = include($dir.'/'.$f);
                    if (($info['locale'] == $name) || ($info['lang_code'] == $name))
                        return $info['lang_number'];
                }
            }
        }
        return 1; // default for vietnamese
    }

    function exponent_lang_get_code($name) {
        $dir = BASE.'subsystems/lang';
        $langs = array();
        if (is_readable($dir)) {
            $dh = opendir($dir);
            while (($f = readdir($dh)) !== false) {
                if (substr($f,-4,4) == '.php') {
                    $info = include($dir.'/'.$f);
                    if (($info['locale'] == $name) || ($info['lang_code'] == $name))
                        return $info['lang_code'];
                }
            }
        }
        return "vi"; // default for vietnamese
    }

    function exponent_lang_exist($name) {
        $dir = BASE.'subsystems/lang';
        $langs = array();
        if (is_readable($dir)) {
            $dh = opendir($dir);
            while (($f = readdir($dh)) !== false) {
                if (substr($f,-4,4) == '.php') {
                    $info = include($dir.'/'.$f);
                    if ($info['lang_code'] == $name)
                        return 1;
                }
            }
        }
        return 0;
    }

    function exponent_lang_initialize() {
        if (!defined('LANG')) {
            if ((is_readable(BASE . 'subsystems/lang/' . USE_LANG . '.php')) && (USE_LANG != 'en_US')) {
                define('LANG', USE_LANG); // Lang file exists.
            } else {
                define('LANG', 'en_US'); // Fallback to 'eng_US' if language file not present.
            }
        }
        
        $info = include(BASE . 'subsystems/lang/' . LANG.'.php');
        
        //setlocale(LC_ALL, $info['locale']);
        
        /**
        * Sep 7, 2011 - trungdt - because, to support cache, 
        * We should load this module not in normal way
        * so, check if DEFAULT_VIEW and LANG_CHARSET has been defined or not
        */
        //DEPRECATED: we no longer use views for i18n
        if (!defined("DEFAULT_VIEW"))
            define('DEFAULT_VIEW', $info['default_view']);
        // For anything related to character sets:
        if (!defined("LANG_CHARSET"))
            define('LANG_CHARSET', $info['charset']);
        if (!defined("LANG_LOCALE"))
            define('LANG_LOCALE', $info['locale']);
        if (!defined("LANG_NUMBER"))
            define('LANG_NUMBER', $info['lang_number']);
        if (!defined("LANG_URL_PREFIX"))
            define('LANG_URL_PREFIX', $info['url_prefix']);
        if (!defined("LANG_CODE"))
            define('LANG_CODE', $info['lang_code']);
        if (!defined("LANG_DIRECTION"))
            define('LANG_DIRECTION', $info['direction']);
        /**
        * Sep 7, 2011 - trungdt - end
        * 
        */
        
        // init common language
        global $_AB_TEMPLATE_DEFAULT;
        $_AB_TEMPLATE_DEFAULT = include(BASE . 'subsystems/lang/' . LANG."/default.php");
    }

    function exponent_lang_loadLangs() {
        $ret = array();
        if (is_readable(BASE.'subsystems/lang')) {		
            while (($lang_file = readfile(BASE . 'subsystems/lang/*.php')) !== false) {
                if (is_readable($lang_file)) {
                    $ret = include($lang_file);
                }
            }
        }	
        return $ret;
    }

    /*
    * Load a set of language keys.
    *
    * @param string $filename The name of the file that should be internationalized.  This should
    * not start with a forward slash and well be taken relative to subsystems/lang/
    *
    * @return Array The language set found, or an empty array if no set file was found.
    */
    //TODO: change api to use a global location object, which tells us module(/other types) and view, then we can do overriding cleanly
    function exponent_lang_loadFile($filename) {
        //so much for having a private function :(
        //we should convert REALLY convert our API to be OO
        if (!function_exists("loadStrings")) {
            //pass-by-reference to shave off a copy operation
            function loadStrings(&$tr_array, $filepath) {
                //TODO: use GPR to allow for local overrides/extensions
                //remove $lang_dir
                //$filepath = array_pop(exponent_core_resolveFilePaths());
                if (is_readable($filepath)) {
                    $tr_array = array_merge($tr_array, include($filepath));
                }
            }
        }


        //initialize the array to be returned
        $_TR = array();


        //set the language directory
        $lang_dir = BASE . 'subsystems/lang/' . LANG;

        // Sep 27, 2011 - trungdt - Fix this bug: when Exponent not found language file needed, we should backup the old language file, in that case, we could load most common language file of current module
        $backup_langdir=$lang_dir;

        // check if the requested language file is installed
        // in that specific language
        // (an incomplete translation)
        if (!file_exists($lang_dir . "/" . $filename)) {

            // If we get to this point,
            // the preferred language file does not exist.  Try english.
            $lang_dir = BASE . 'subsystems/lang/eng_US';
        }

        //load module specific strings
        $path_components = explode("/", $filename);
        //as the typical path will be something like modules/somemodule/views/someview.php it must be 1
        $module = array();
        if (count($path_components) > 1) {
            $module = $path_components[1];
        }

        //load the view specific strings
        loadStrings($_TR, $lang_dir . "/" . $filename);

        // load most common language default for this module, in current language
        loadStrings($_TR, $backup_langdir . "/modules/" . $module . "/common.php");

        /**
        * Sep 8, 2011 - trungdt - Move this line code to here - begin 
        */
        global $_AB_TEMPLATE_DEFAULT;
        $_TR=array_merge($_TR, $_AB_TEMPLATE_DEFAULT);
        /**
        * Sep 8, 2011 - trungdt - Move this line code to here - End
        */
        
        return $_TR;
    }


    /*
    * Return a single key from a language set.
    *
    * @param string $filename The name of the file that should be internationalized.  This should
    * not start with a forward slash and well be taken relative to subsystems/lang/
    * @param string $key The name of the language key to return.
    *
    * @return Array The language set found, or an empty array if no set file was found.
    */
    function exponent_lang_loadKey($filename, $key) {
        // First we load the full set.
        $keys = exponent_lang_loadFile($filename);

        // return either the looked-up value
        // or if non-existent
        // the key itself, so there is a visual indicator
        // of a missing translation
        if($keys[$key] != null) {
            $return_value = $keys[$key];
        } else {
            $return_value = $key;
        }

        return $return_value;
    }

    /*
    * Return a short language code from a long one, many external programs use the short ones
    * its a dumb, straight table lookup function, no fancy regexp rules.
    * It should rather be replaced by introducing a short lang code to the language descriptor files
    * and replacing the site wide CONSTANTS by global objects, which then in return
    * could have a multitude of subobjects and properties, such as long and short codes
    * 
    * @param string $long_code something like "eng_US"
    *
    * @return string the short version of the lang code
    */
    function exponent_lang_convertLangCode($long_code, $target = "iso639-1") {
        //TODO: auto-guess the incoming type of lang code from the input format
        //TODO: breakout the data into a xml file in subsystems/lang/

        //assume that we are getting an iso639-2_Country code for now(standard for eXp's i18n)
        switch ($long_code) {
            case "deu_DE":
                $iso639_1 = "de";
                $iso639_2 = "deu";
                break;
            case "eng_US":
                $iso639_1 = "en";
                $iso639_2 = "eng";
                break;
            default:
                $iso639_1 = "vi";
                $iso639_2 = "viet";
        }

        //resist the temptation to do eval()
        switch ($target) {
            case "iso639-1":
                $converted_code = $iso639_1;
                break;
            case "iso639-2":
                $converted_code = $iso639_2;
                break;
        }

        return $converted_code;
    }

    /**
    * return default lang text
    * @return string
    * OLD CODE
    * Sep 8, 2011 - trungdt - Change exponent_lang_getText and load default language on init
    function exponent_lang_getText($text) 
    {
    // add default language file text
    $ilang=exponent_lang_loadFile("default.php");
    if (isset($ilang[$text]))
    {
    return $ilang[$text];
    }
    else
    {
    return $text;
    }

    }
    */
    function exponent_lang_getText($text) 
    {
        global $_AB_TEMPLATE_DEFAULT;
        if (isset($_AB_TEMPLATE_DEFAULT[$text]))
        {
            return $_AB_TEMPLATE_DEFAULT[$text];
        }
        else
        {
            return $text;
        }

    }
    /**
    * Sep 8, 2011 - trungdt - End
    */

    /**
    * Get language of section host of the selected location
    * 
    * @param json $loc
    * @return string
    * @copyright trungdt
    * @since June 9
    */
    function exponent_lang_getLang_from_Object($loc)
    {
        global $db;
        
        if (!is_object($loc))
            $loc = unserialize($loc);
        // just get src and query into sectionref
        $data = $db->selectObject("sectionref","source = '{$loc->src}'");
        
        if (!$data){
            return "";
        }
        else{
            $section = $db->selectObject("section","id = {$data->section}");
            if (!$section)
                return "";
            else
                return $section->language;
        }
        
        return;
        
        if (is_object($loc))
            $loc = serialize($loc);
            
        $data = $db->selectObject("container","internal = '{$loc}'");
        if (!$data)
        {
            return "";
        }
        else
        {
            // get language list
            $lang_list = exponent_lang_list();

            $ex = $data->external;

            // fixed container
            $int = unserialize($data->internal);
            $src = $int->src;
            
            $src_ex ="";
            if ($data->external != "N;")
                $src_ex = unserialize($data->external)->src;
                
            foreach ($lang_list as $k=>$v)
                if (((strlen($src)>strlen($k)) && (substr($src,0,-strlen($k))== $k)) ||
                ((strlen($src_ex)>strlen($k)) && (substr($src_ex,0,-strlen($k))== $k)))
                {
                    return $k;
                    break;
                }
            // still not found :) then we look for section
            if ($src_ex =="")
                $src_ex = $src;
            $data = $db->selectObject("sectionref","source = '{$src_ex}'");
            if (!$data)
            {
                return "";
            }
            else{
                $data = $db->selectObject("section","id = {$data->section}");
                if (!$data)
                    return "";
                else
                    return $data->language;
            }
        }
    }
    
    /**
    * Extract language prefix 
    * 
    * @param mixed $url
    */
    function exponent_lang_extract_prefix_fromURL($url){
      // extract URL_FULL
      $a=strlen(URL_FULL);
      if ((strlen($url)> $a)  
        &&(substr($url,0,$a) == URL_FULL ))
        {
            $url=substr($url, $a);
        }
      
      if (substr($url,0,1) == "/")
        $url=substr($url, 1);
      
      $t=strpos($url, "/");
      if ($t > 0)
      {
          return substr($url, 0,$t);
      }
      else
        return $url;
      
      
    }
?>
